import datetime

from django.http import HttpResponse

from common.db_util import MySqlDb


def get_session(request,key):
    try:
        value = request.session[key]
        return value
    except KeyError:
        # 如果没有找到 key，则返回 None 或其他默认值
        return None
"""用户登录后鉴权中间件"""
class AuthMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        print("============访问了中间件 author middleware===========")
        exclude_urls = ["/page/sys/user/to_login/","/api/sys/user/login/"]

        #排除url
        if request.path_info in exclude_urls:
            response = self.get_response(request)
            return response
        #通过session检查是否有合法的权限
        login_flag=get_session(request,"login_flag")
        if login_flag!= 'have_login':
            return HttpResponse("<script>alert('用户会话信息已失效，请先登录！');window.location.href='/page/sys/user/to_login/';</script>")
        else:
            user = get_session(request, "user_info")
            print("用户已登录，用户信息:",user)

            response = self.get_response(request)
            return response


